package com.jrx.anytxn.investor.timer.job.fundRoute.step;

import com.jrx.anytxn.investor.bean.InvestorFundRouteBean;
import com.jrx.anytxn.investor.entity.TlFundRestraintLog;
import com.jrx.anytxn.investor.entity.TlFundRouteLog;
import com.jrx.anytxn.investor.entity.TlInvestorLoanApproveLog;
import com.jrx.anytxn.investor.mapper.ext.ExtTlFundRestraintLogMapper;
import com.jrx.anytxn.investor.mapper.ext.ExtTlFundRouteLogMapper;
import com.jrx.anytxn.investor.mapper.ext.ExtTlInvestorLoanApproveLogMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.item.ItemWriter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 资金源路由 - writer
 *
 * @author liuyang
 * @date 2020-06-05
 */
@Service
public class InvestorFundRouteWriter implements ItemWriter<InvestorFundRouteBean> {

    @Resource
    private ExtTlFundRouteLogMapper fundRouteLogMapper;

    @Resource
    private ExtTlFundRestraintLogMapper fundRestraintLogMapper;

    @Resource
    private ExtTlInvestorLoanApproveLogMapper investorLoanApproveLogMapper;

    @Override
    public void write(List items) {

        List<TlFundRouteLog> updateFundRouteLogs = new ArrayList<>();

        List<TlFundRestraintLog> fundRestraintLogs = new ArrayList<>();

        List<TlInvestorLoanApproveLog> investorLoanApproveLogs = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(items)) {
            for (Object obj : items) {
                InvestorFundRouteBean bean = (InvestorFundRouteBean)obj;
                if(bean.getUpdateFundRouteLog() != null) {
                    updateFundRouteLogs.add(bean.getUpdateFundRouteLog());
                }
                if(CollectionUtils.isNotEmpty(bean.getFundRestraintLogs())) {
                    fundRestraintLogs.addAll(bean.getFundRestraintLogs());
                }
                if(CollectionUtils.isNotEmpty(bean.getInvestorLoanApproveLogs())) {
                    investorLoanApproveLogs.addAll(bean.getInvestorLoanApproveLogs());
                }
            }
        }

        if (CollectionUtils.isNotEmpty(updateFundRouteLogs)) {
            fundRouteLogMapper.batchUpdateForBatch(updateFundRouteLogs);
        }

        if (CollectionUtils.isNotEmpty(fundRestraintLogs)) {
            fundRestraintLogMapper.batchInsert(fundRestraintLogs);
        }

        if (CollectionUtils.isNotEmpty(investorLoanApproveLogs)) {
            investorLoanApproveLogMapper.batchInsert(investorLoanApproveLogs);
        }
    }
}
